package com.ray.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.appengine.api.search.query.ExpressionParser.negation_return;
import com.google.appengine.repackaged.com.google.gson.JsonObject;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.ReceiptPaymentRecordBean;
import com.ray.bean.TableData;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.bean.WarehouseInSumMoneyBean;
import com.ray.exception.ServiceException;
import com.ray.service.FinanceService;
import com.ray.service.WarehouseInSumMoneyService;
import com.ray.util.ExcelExportUtil;
import com.ray.util.RequestUtil;
import com.ray.util.ResponseUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.ray.util.TimeAndUnix;


/**
 * 财务模块中的出入库
 * <p>Title: WarehouseInSumMoney</p>  
 * <p>Description: </p>  
 * @author 李斌  
 * @date 2018年5月23日
 */
@Controller
@RequestMapping("/warehouseInSumMoney")
public class WarehouseInSumMoneyController {
	
	@Autowired
	private WarehouseInSumMoneyService warehouseInSumMoneyService;
	@Autowired
	private FinanceService financeService;
	
	@ResponseBody
	@RequestMapping("/getWarehouseInSumMoneyDetail")
	public Map<String,Object> getWarehouseInSumMoneyDetail(HttpServletRequest request) throws ServiceException{
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		DatatablesViewPageBean<WarehouseInSumMoneyBean> warehouseInSumList = warehouseInSumMoneyService.getWarehouseInSumMoneyDetail(map);
		Map<String,Object> data = new HashMap<String,Object>();
		if(map.get("isSum")!=null) {
			data=warehouseInSumMoneyService.getSumMoneyByWarehouseSum(map);
			data=data==null?new HashMap():data;
			map.put("startDate", simpleDateFormat.format(TimeAndUnix.getmindate()));
			map.put("endDate", simpleDateFormat.format(TimeAndUnix.getmaxdate()));
			Map<String,Object> thisMonthMap=warehouseInSumMoneyService.getSumMoneyByWarehouseSum(map); 
			thisMonthMap=thisMonthMap == null?new HashMap<String,Object>():thisMonthMap;
			data.put("monthSum", thisMonthMap.get("sum"));
			data.put("monthTeceiptPaymentPrice", thisMonthMap.get("receiptPaymentPrice"));
		}
		data.put("list",warehouseInSumList);
		return ResponseUtil.ResponseResult(data); 
	}
	
	
	@ResponseBody
	@RequestMapping("/getAccountPayableSum")
	public Map<String,Object> getAccountPayableSum(HttpServletRequest request) throws ServiceException{
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(warehouseInSumMoneyService.getAccountPayableSum(map)); 
	}
	
	
	@ResponseBody
	@RequestMapping("/getWarehouseOutBalanceData")
	public Map<String,Object> getWarehouseOutBalanceData(HttpServletRequest request) throws ServiceException{
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		DatatablesViewPageBean<WarehouseInSumMoneyBean> warehouseInSumList = warehouseInSumMoneyService.getWarehouseOutBalanceData(map);
		Map<String,Object> data = new HashMap<String,Object>();
		if(map.get("isSum")!=null) {
			data=warehouseInSumMoneyService.getWarehouseOutBalanceSumMoney(map);
			data=data==null?new HashMap():data;
			map.put("startDate", simpleDateFormat.format(TimeAndUnix.getmindate()));
			map.put("endDate", simpleDateFormat.format(TimeAndUnix.getmaxdate()));
			Map<String,Object> thisMonthMap=warehouseInSumMoneyService.getWarehouseOutBalanceSumMoney(map); 
			thisMonthMap=thisMonthMap == null?new HashMap<String,Object>():thisMonthMap;
			data.put("monthSum", thisMonthMap.get("sum"));
			data.put("monthTeceiptPaymentPrice", thisMonthMap.get("receiptPaymentPrice"));
		}
		data.put("list",warehouseInSumList);
		return ResponseUtil.ResponseResult(data); 
	}
	
	/**
	 * 获取出库财务汇总
	 * @param request
	 * @return
	 * @throws ServiceException
	 */
	@ResponseBody
	@RequestMapping("/getWarehouseOutBalanceSum")
	public Map<String,Object> getWarehouseOutBalanceSum(HttpServletRequest request) throws ServiceException{
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(warehouseInSumMoneyService.getWarehouseOutBalanceSum(map)); 
	}
	
	/**
	 * 获取公司仓库制单人
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getWarehouseUserList")
	public Map<String,Object> getWarehouseUserList(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(warehouseInSumMoneyService.getWarehouseUserList(map)); 
	}
	
	/**
	 * 获取公司收付款方式
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getPaymentModeList")
	public Map<String,Object> getPaymentModeList(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		return ResponseUtil.ResponseResult(warehouseInSumMoneyService.getPaymentModeList(map)); 
	}
	
	/**
	 * 修改入库结算状态(是否结算)
	* @date 2018年5月25日 上午9:10:00 
	* @author 李斌
	* @return Map<String,Object> 
	* @throws
	 */
	@ResponseBody 
	@RequestMapping("/setIsBalanceByWarehouseInSumId")
	public Map<String,Object> setIsBalanceByWarehouseInSumId(HttpServletRequest request) throws ServiceException{
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		boolean flag = warehouseInSumMoneyService.setIsBalanceByWarehouseInSumId(map);
		if(flag) { 
			return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
		}else { 
			return ResponseUtil.ResponseError(ReturnStringUtil.UPDATE_ERROR);
		}
	}
	
	
	/**
	 * 保存收付款记录
	 * inOutId 出入库id
	 * @author nate 
	 */
	@ResponseBody 
	@RequestMapping("/getReceiptPaymentRecordByInOutId")
	public Map<String,Object> getReceiptPaymentRecordByInOutId(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseInSumMoneyService.getReceiptPaymentRecordByInOutId(map));
	}
	
	/**
	 * 获取收付款记录
	 * startTime 开始时间
	 * endTime 结束时间
	 * type 类型  1 收款  2 付款
	 * receiptPaymentMode 收付款方式
	 * createUser 经手人
	 * start 分页参数
	 * length 分页参数
	 * isSum 是否求和  传任意值则求和，不传或未''则不求和(点击分页和刷新列表时不需求和)
	 * status 状态
	 * @author nate 
	 */
	@ResponseBody 
	@RequestMapping("/getReceiptPaymentRecord")
	public Map<String,Object> getReceiptPaymentRecord(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseInSumMoneyService.getReceiptPaymentRecord(map));
	}
	
	/**
	 * 获取收付款经手人
	 * @author nate 
	 */
	@ResponseBody 
	@RequestMapping("/getReceiptPaymentRecordUser")
	public Map<String,Object> getReceiptPaymentRecordUser(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseInSumMoneyService.getReceiptPaymentRecordUser(map));
	}
	
	
	
	
	/**
	 jsonObject{
	     sumMoney:0,  --付款总金额
	     type:1,  --1收款，2付款
	     payType:1, --1只生成记录  2审核过账
	     conversionPrice:0, --折算金额
	     receiptPaymentMode:'', -- 收付款方式
	     detail：[
	         {
	           inOutId：xxx, -- 出入库id
	           price：0, --金额单笔金额
	           addReducePrice:0, -- 增减金额（附加）
	           addReduceType:1, -- 增减类型 （附加）
	           addReduceReason:'' -- 增减原因 （附加）
	         }
	     ]
	 }
	 * sumMoney  
	 * 保存收付款记录
	 * inOutId 出入库id
	 * type 类型  1 收款  2 付款
	 * price 金额
	 * receiptPaymentMode 收付款方式
	 * payType 操作方式 1只生成记录  2 生成记录并审核
	 * 改为批量  jsonArray  
	 * @author nate 
	 */
	@ResponseBody 
	@RequestMapping("/saveReceiptPaymentRecord")
	public Map<String,Object> saveReceiptPaymentRecord(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		financeService.saveReceiptPaymentRecord(map);
		
//		StringUtil.checkIsTrue(map, "jsonArray", "未获取到数据");
//		String jsonStr = map.get("jsonArray").toString();
//		String groupId  = StringUtil.getUUID();
//		map.put("groupId", groupId);
//		JSONArray jsonArray = JSONArray.fromObject(jsonStr);
//		for(int i = 0 ; i < jsonArray.size() ; i++ ) {
//			JSONObject jsonObject = jsonArray.getJSONObject(i);
//			Map<String, Object> oneMap = new HashMap<String,Object>(map);
//		    oneMap.put("inOutId", jsonObject.get("inOutId"));
//		    oneMap.put("type", jsonObject.get("type"));
//		    oneMap.put("price", jsonObject.get("price"));
//		    oneMap.put("receiptPaymentMode", jsonObject.get("receiptPaymentMode"));
//		    oneMap.put("payType", jsonObject.get("payType"));
//		    warehouseInSumMoneyService.saveReceiptPaymentRecord(oneMap);
//		}
		return ResponseUtil.ResponseResult(ReturnStringUtil.OPERATION_SUCCESS);
	}
	
	
	/**
	 * 审核收付款记录
	 * id 出入库id
	 * status 状态 1通过 2 不通过
	 * @author nate 
	 */
	@ResponseBody 
	@RequestMapping("/approvalReceiptPaymentRecord")
	public Map<String,Object> approvalReceiptPaymentRecord(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		warehouseInSumMoneyService.approvalReceiptPaymentRecord(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.APPROVAL_SUCCESS);
	}
	
	
	
	/**
	 * 删除收付款记录
	 * id 出入库id
	 * @author nate 
	 */
	@ResponseBody 
	@RequestMapping("/deleteReceiptPaymentRecord")
	public Map<String,Object> deleteReceiptPaymentRecord(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		warehouseInSumMoneyService.deleteReceiptPaymentRecord(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.DELETE_SUCCESS);
	}
	
	/**
	 * 修改收付款记录
	 * id 出入库id
	 * price 价格
	 * @author nate 
	 */
	@ResponseBody 
	@RequestMapping("/updateReceiptPaymentRecord")
	public Map<String,Object> updateReceiptPaymentRecord(HttpServletRequest request){
		Map<String,Object> map = RequestUtil.getRequestParamByGeneric(request);
		warehouseInSumMoneyService.updateReceiptPaymentRecord(map);
		return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
	}
	
	/**
	 * 获取单个出入库详情，已付款和未付款数量
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getOneWarehousePayMentDetail")
	public  Map getOneWarehousePayMentDetail(HttpServletRequest request) {
		Map map=RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseInSumMoneyService.getOneWarehousePayMentDetail(map));
	}
	
	
	/**
	 * 获取财务报表
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getFinancialStatements")
	public  Map getFinancialStatements(HttpServletRequest request) {
		Map map=RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseInSumMoneyService.getFinancialStatements(map));
	}
	
	
	/**
	 * 获取财务报表
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/exportWarehouseInSumMoneyDetail")
	public  Map exportWarehouseInSumMoneyDetail(HttpServletRequest request) {
		Map map=RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(warehouseInSumMoneyService.getFinancialStatements(map));
	}
	
	
	//下载员工达成率数据
	@RequestMapping(value="/exportWarehouseInSumMoneyDetail",method=RequestMethod.GET)
	@ResponseBody
	public void exportWarehouseInSumMoneyDetail(HttpServletRequest request,HttpServletResponse response) throws ServiceException, CloneNotSupportedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		Map map=RequestUtil.getRequestAllParam(request);
		map.put("start", null);
		map.put("length", null);
		DatatablesViewPageBean<WarehouseInSumMoneyBean> datatablesViewPageBean = warehouseInSumMoneyService.getWarehouseInSumMoneyDetail(map);
		List<WarehouseInSumMoneyBean> tableList=datatablesViewPageBean.getReturnData();
		for(WarehouseInSumMoneyBean xx:tableList) {
			xx.setTypeStr();
			xx.setBalanceStr();
			xx.setIsTaxStr();
		}
		String [] tableHeadFields={"入库类型","采购单号","订单编号","工厂型号","客户型号","供应商","物料名称","物料类型","规格型号","编号","描述","物料部门","入库单位","入库单价","采购单价","数量","入库金额","已付金额","增减金额","是否结算","结算金额","预计结算日期","下单时间","采购时间","入库日期","结算时间","制单人","是否含税"};
		String [] fields={"typeStr","purchaseId","orderId","factoryNo","coustomId","providerName","materialName","materialType","model","color","colorDescription","materialDeptName","inCountUnit","inCountPrice","unitPrice","count","inOutMoney","receiptPaymentPrice","addReducePrice","balanceStr","money","payTime","inCountTime","purchaseTime","inDay","balanceTime","createUser","isTaxStr"};
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		File excelFile=ExcelExportUtil.createExcelFile(tableList,tempFolder,tableHeadFields,fields);
		ResponseUtil.downloadfile(response, excelFile, "材料应付.xlsx", true);
	}
	
	
	//下载员工达成率数据
	@RequestMapping(value="/exportWarehouseOutSumMoneyDetail",method=RequestMethod.GET)
	@ResponseBody
	public void exportWarehouseOutSumMoneyDetail(HttpServletRequest request,HttpServletResponse response) throws ServiceException, CloneNotSupportedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		Map map=RequestUtil.getRequestAllParam(request);
		map.put("start", null);
		map.put("length", null);
		DatatablesViewPageBean<WarehouseInSumMoneyBean> datatablesViewPageBean = warehouseInSumMoneyService.getWarehouseOutBalanceData(map);
		List<WarehouseInSumMoneyBean> tableList=datatablesViewPageBean.getReturnData();
		for(WarehouseInSumMoneyBean xx:tableList) {
			xx.setBalanceStr();
			xx.setIsTaxStr();
		}
		String [] tableHeadFields={"出库单号","订单编号","工厂型号","客户型号","客户","物料名称","物料类型","规格型号","编号","描述","物料部门","出库单位","出库单价","数量","出库金额","已收金额","增减金额","是否结算","结算金额","预计收款日期","出库时间","结算时间","制单人","是否含税"};
		String [] fields={"id","orderId","factoryNo","coustomId","providerName","materialName","materialType","model","color","colorDescription","materialDeptName","inCountUnit","outCountPrice","count","inOutMoney","receiptPaymentPrice","addReducePrice","balanceStr","money","payTime","createTime","balanceTime","createUser","isTaxStr"};
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		File excelFile=ExcelExportUtil.createExcelFile(tableList,tempFolder,tableHeadFields,fields);
		ResponseUtil.downloadfile(response, excelFile, "应收账款.xlsx", true);
	}
	
	
	
	
	
	
	
	
}
